﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using Lion.WeiXin.Core.Data;
using Lion.WeiXin.Core.Models;
using Lion.WeiXin.Core;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Lion.WeiXin.Tools.Log;
using Lion.WeiXin.Tools;
using System.Collections;
using System.Globalization;
namespace Lion.WeiXin.Controllers
{
    [PermissionFilter]
    public class ProductController : Controller
    {
        IProduct ipro = new ProductDAO();
        Lion.WeiXin.Core.Data.IDictionary idic = new DictionaryDAO();
        DBContext db = new DBContext();

        public ActionResult Index()
        {
            InitProductType(0);
            return View();
        }

        /// <summary>
        ///  获取分页列表数据
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="msgType"></param>
        /// <param name="currentPage"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        public string GetPageList(string title, int productType, int currentPage, int pageSize)
        {
            //数据量少的，直接查全部数据分页展示           
            int totalCount = 0;
            title = HttpUtility.UrlDecode(title);
            //如果传入条件参数
            List<ProductModel> list = new List<ProductModel>();
            string where = " 1=1 ";
            if (!string.IsNullOrEmpty(title))
            {
                where += string.Format(" and Name like '%{0}%' ", title);
            }
            if (productType > 0)
            {
                where += string.Format(" and Dic_ProductType = {0} ", productType);
            }

            list = db.Products.GetList(pageSize, currentPage, where);
            totalCount = db.Products.GetRecordCount(where);

            //处理产品类型名称
            List<DictionaryModel> dic_pro_types = idic.GetList("Dic_Key like '100%' and len(Dic_Key)=6");
            for (int i = 0; i < list.Count; i++)
            {
                DictionaryModel temp = dic_pro_types.FirstOrDefault(n => n.AID == list[i].Dic_ProductType);
                if (temp!=null)
                {
                    list[i].ProductType = temp.Dic_Value;
                }
            }


            string jsonResult = JsonConvert.SerializeObject(list, new IsoDateTimeConverter());
            jsonResult = "{\"total\":" + totalCount + "," + "\"data\":" + jsonResult + "}";
            return jsonResult;
        }


        public ActionResult Show()
        {
            string ID = Request.QueryString["ID"];
            if (string.IsNullOrEmpty(ID))
            {
                return Redirect(Request.RawUrl);
            }

            int productID = int.Parse(ID);
            ProductModel model = ipro.GetModel(productID);
            InitProductType(model.Dic_ProductType);
            return View(model);
        }


        public ActionResult Create()
        {
            InitProductType(0);
            return View();
        }

        private void InitProductType(int selectID)
        {
            //加载产品类型
            List<DictionaryModel> dic_pro_types = idic.GetList("Dic_Key like '100%' and Dic_Key<>'100'");
            List<SelectListItem> selectTypes = new List<SelectListItem>();

            selectTypes.Add(new SelectListItem() { Value = "0", Text = "请选择" });

            foreach (DictionaryModel item in dic_pro_types)
            {
                if (item.AID == selectID)
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Dic_Value, Selected = true });
                }
                else
                {
                    selectTypes.Add(new SelectListItem() { Value = item.AID.ToString(), Text = item.Dic_Value });
                }
            }
            ViewData["selProductType"] = selectTypes;
        }

        [ValidateInput(false)] //kindEditor 需要取消这个验证
        public ActionResult Save(ProductModel model)
        {
            ActionEnum action = ActionEnum.Create;
            if (model.AID > 0)
            {
                action = ActionEnum.Update;
            }
            string result = SaveStateEnum.OK.ToString();

            try
            {
                if (action == ActionEnum.Create)
                {
                    model.Creator = CurrentUser.UserName;
                    model.Code = StringHelper.GetRandNumber();
                    if (!ipro.Exists(model.Code))
                    {
                        ipro.Add(model);
                    }
                }
                else if (action == ActionEnum.Update)
                {
                    ipro.Update(model);
                }
                else
                {
                    result = SaveStateEnum.NO.ToString();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "数据{0}失败", action);
                result = SaveStateEnum.NO.ToString();
            }

            return Content(result);
        }

        public ActionResult Delete(string IDs)
        {
            string result = SaveStateEnum.NO.ToString();
            try
            {
                if (!string.IsNullOrEmpty(IDs))
                {
                    //删除图片文件
                    List<ProductModel> delProducts = ipro.GetList("p.AID in (" + IDs + ")");
                    foreach (ProductModel item in delProducts)
                    {
                        string filePath = Server.MapPath(item.Image);
                        if (System.IO.File.Exists(filePath))
                        {
                            System.IO.File.Delete(filePath);
                        }
                    }

                    ipro.DeleteList(IDs);
                    result = SaveStateEnum.OK.ToString();
                    // System.IO.File.Delete();
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex, "删除数据失败!");
            }
            return Content(result);
        }

        /// <summary>
        /// 编辑器上传图片
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult UploadImage()
        {
            string savePath = "/Content/UpImages/Products/";
            string saveUrl = "/Content/UpImages/Products/";
            string fileTypes = "gif,jpg,jpeg,png,bmp";
            int maxSize = 1000000;

            Hashtable hash = new Hashtable();

            HttpPostedFileBase file = Request.Files["imgFile"];
            if (file == null)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "请选择文件";
                return Json(hash);
            }

            string dirPath = Server.MapPath(savePath);
            if (!Directory.Exists(dirPath))
            {
                //hash = new Hashtable();
                //hash["error"] = 0;
                //hash["url"] = "上传目录不存在";
                //return Json(hash);
                Directory.CreateDirectory(dirPath);
            }

            string fileName = file.FileName;
            string fileExt = Path.GetExtension(fileName).ToLower();

            ArrayList fileTypeList = ArrayList.Adapter(fileTypes.Split(','));

            if (file.InputStream == null || file.InputStream.Length > maxSize)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "上传文件大小超过限制";
                return Json(hash);
            }

            if (string.IsNullOrEmpty(fileExt) || Array.IndexOf(fileTypes.Split(','), fileExt.Substring(1).ToLower()) == -1)
            {
                hash = new Hashtable();
                hash["error"] = 0;
                hash["url"] = "上传文件扩展名是不允许的扩展名";
                return Json(hash);
            }
            Random rd = new Random(DateTime.Now.GetHashCode());

            // string newFileName = DateTime.Now.ToString("yyyyMMddHHmmss_ffff", DateTimeFormatInfo.InvariantInfo) + fileExt;
            string newFileName = string.Format("{0}_{1}{2}", DateTime.Now.ToString("yyyyMMddHHmmss_ffff"), rd.Next(1, 10000), fileExt);
            string filePath = dirPath + newFileName;
            file.SaveAs(filePath);
            string fileUrl = saveUrl + newFileName;

            hash = new Hashtable();
            hash["error"] = 0;
            hash["url"] = fileUrl;

            return Json(hash, "text/html;charset=UTF-8");
        }

        public JsonResult GetProducts()
        {

            List<DictionaryModel> list = new List<DictionaryModel>();
            list = db.Dictionarys.GetList(string.Format(" IsDelete=0 and Dic_Key like '{0}%' and len(Dic_Key)={1}", "100", 6));
            List<ProductType> ptList = new List<ProductType>();
            foreach (DictionaryModel dic in list)
            {

            }
            return Json(new { data = list });
        }

        public JsonResult GetProduct(int productId)
        {
            ProductModel model = db.Products.GetModel(productId);
            if (model != null)
            {
                return Json(new { code = SaveStateEnum.OK.ToString(), data = model });
            }
            else {
                return Json(new { code = SaveStateEnum.NO.ToString() });
            }
        }
    }
}
